<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElForm } from "element-plus";
import {
  Search,
  RefreshLeft,
  Plus,
  Edit,
  Delete,
} from "@element-plus/icons-vue";
import axios from "axios";

// 创建axios实例
const api = axios.create({
  baseURL: "/api", // 基础URL
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    ElMessage.error(error.message || "请求失败");
    return Promise.reject(error);
  }
);

// 搜索条件
const searchForm = reactive({
  deptName: "",
  status: "",
});

// 部门数据
const deptList = ref([]);
// 加载状态
const loading = ref(false);
// 表格加载状态
const tableLoading = ref(false);
// 跳转到指定页的页码
const jumpPage = ref(1);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 20,
  pageSizes: [10, 20, 50, 100],
});

// 获取部门列表
const getDeptList = async () => {
  tableLoading.value = true;
  try {
    // 将中文状态转换为数字类型
    const statusValue =
      searchForm.status === "正常"
        ? 1
        : searchForm.status === "停用"
        ? 0
        : searchForm.status;
    const response = await api.get(
      `depts?name=${searchForm.deptName}&status=${statusValue}&page=${pagination.currentPage}&pageSize=${pagination.pageSize}`
    );
    // 适配后端响应格式
    if (response.code === 1 && Array.isArray(response.data.rows)) {
      // 映射字段名：name -> deptName, updateTime -> lastModifiedTime
      deptList.value = response.data.rows.map((item) => ({
        id: item.id,
        deptName: item.name,
        status: item.status === 1 ? "正常" : "停用",
        lastModifiedTime: item.updateTime,
        createTime: item.createTime,
      }));
      // 修复总记录数设置，使用正确的字段
      pagination.total = response.data.total || 0;
    } else {
      deptList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
    ElMessage.error("获取部门列表失败");
  } finally {
    tableLoading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  pagination.currentPage = 1; // 搜索时重置到第一页
  getDeptList();
};

// 清空搜索条件
const handleReset = () => {
  searchForm.deptName = "";
  searchForm.status = "";
  pagination.currentPage = 1;
  getDeptList();
};

// 新增部门对话框相关
const addDialogVisible = ref(false);
const addFormData = reactive({
  deptName: "",
  status: "",
});
const addFormRef = ref();

// 修改部门对话框相关
const editDialogVisible = ref(false);
const editFormData = reactive({
  id: "",
  deptName: "",
  status: "",
});
const editFormRef = ref();

// 表单验证规则
const rules = {
  deptName: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  status: [{ required: true, message: "请选择部门状态", trigger: "change" }],
};

// 添加部门
const handleAdd = () => {
  // 重置表单
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  addDialogVisible.value = true;
};

// 修改部门
const handleEdit = (id) => {
  // 找到要修改的部门
  const dept = deptList.value.find((item) => item.id === id);
  if (dept) {
    // 复制数据到表单
    editFormData.id = dept.id;
    editFormData.deptName = dept.deptName;
    editFormData.status = dept.status;
    // 打开对话框
    editDialogVisible.value = true;
  }
};

// 提交新增部门
const submitAdd = async () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 映射请求数据格式
      const requestData = {
        name: addFormData.deptName,
        status: addFormData.status === "正常" ? 1 : 0,
      };
      api
        .post("depts", requestData)
        .then((response) => {
          if (response.code === 1) {
            // 关闭对话框
            addDialogVisible.value = false;
            // 重新加载列表
            getDeptList();
            // 显示成功消息
            ElMessage.success("新增部门成功");
          } else {
            ElMessage.error(response.msg || "新增失败");
          }
        })
        .catch((error) => {
          console.error("新增部门失败:", error);
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

// 提交修改部门
const submitEdit = async () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 映射请求数据格式
      const requestData = {
        id: editFormData.id,
        name: editFormData.deptName,
        status: editFormData.status === "正常" ? 1 : 0,
      };
      api
        .put("depts", requestData)
        .then((response) => {
          if (response.code === 1) {
            // 关闭对话框
            editDialogVisible.value = false;
            // 重新加载列表
            getDeptList();
            // 显示成功消息
            ElMessage.success("修改部门成功");
          } else {
            ElMessage.error(response.msg || "修改失败");
          }
        })
        .catch((error) => {
          console.error("修改部门失败:", error);
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

// 删除部门
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该部门吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      api
        .delete(`depts/${id}`)
        .then((response) => {
          if (response.code === 1) {
            // 重新加载列表
            getDeptList();
            // 显示成功消息
            ElMessage.success(response.msg || "删除成功");
          } else {
            ElMessage.error(response.msg || "删除失败");
          }
        })
        .catch((error) => {
          console.error("删除部门失败:", error);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
};

// 分页变化处理
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getDeptList();
};

const handleCurrentChange = (current) => {
  pagination.currentPage = current;
  getDeptList();
};

// 跳转到指定页
const handleJump = (page) => {
  if (page >= 1 && page <= Math.ceil(pagination.total / pagination.pageSize)) {
    pagination.currentPage = page;
    getDeptList();
  } else {
    ElMessage.warning("请输入有效的页码");
  }
};

// 页面挂载时加载数据
onMounted(() => {
  getDeptList();
});
</script>

<template>
  <div class="dept-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-form">
        <el-form :inline="true">
          <el-form-item label="部门名称：">
            <el-input
              v-model="searchForm.deptName"
              placeholder="请输入部门名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择"
              style="width: 150px"
            >
              <el-option label="正常" value="正常"></el-option>
              <el-option label="停用" value="停用"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch"
              ><el-icon><Search /></el-icon> 搜索</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset"
              ><el-icon><RefreshLeft /></el-icon> 清空</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="action-area">
        <el-button type="primary" @click="handleAdd"
          ><el-icon><Plus /></el-icon> 添加部门</el-button
        >
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="deptList"
        :loading="tableLoading"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="序号"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="deptName"
          label="部门名称"
          min-width="180"
          align="center"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <span
              :class="
                scope.row.status === '正常'
                  ? 'status-normal'
                  : 'status-disabled'
              "
            >
              {{ scope.row.status }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="lastModifiedTime"
          label="最后修改时间"
          min-width="180"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.row.id)"
              class="text-primary"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="handleDelete(scope.row.id)"
              class="text-danger"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <div class="pagination-info">
        共 {{ pagination.total }} 条记录 第 {{ pagination.currentPage }} /
        {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes"
          layout="prev, pager, next, sizes"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
      <div class="jump-to">
        <span>跳至</span>
        <el-input-number
          v-model="jumpPage"
          :min="1"
          :max="Math.ceil(pagination.total / pagination.pageSize)"
          :step="1"
          :controls-position="'right'"
          size="small"
        ></el-input-number>
        <span>页</span>
        <el-button size="small" @click="handleJump(jumpPage)">确定</el-button>
      </div>
    </div>

    <!-- 新增部门对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增部门"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="*部门名称：" prop="deptName">
          <el-input
            v-model="addFormData.deptName"
            placeholder="请输入部门名称"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="*部门状态：" prop="status">
          <el-select
            v-model="addFormData.status"
            placeholder="请选择"
            style="width: 300px"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="停用" value="停用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd" :loading="loading"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 修改部门对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改部门"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="*部门名称：" prop="deptName">
          <el-input
            v-model="editFormData.deptName"
            placeholder="请输入部门名称"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="*部门状态：" prop="status">
          <el-select
            v-model="editFormData.status"
            placeholder="请选择"
            style="width: 300px"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="停用" value="停用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="loading"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
}

.action-area {
  display: flex;
  align-items: center;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  padding: 20px 0;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

:deep(.el-pagination) {
  margin: 0;
}

:deep(.el-pagination__sizes) {
  margin-left: 10px;
}

.status-normal {
  color: #67c23a;
}

.status-disabled {
  color: #f56c6c;
}

/* 按钮样式调整 */
.text-warning {
  color: #e6a23c !important;
}

.text-success {
  color: #67c23a !important;
}

.text-primary {
  color: #409eff !important;
}

.text-danger {
  color: #f56c6c !important;
}

/* 表格样式优化 */
:deep(.el-table__header th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

/* 分页器样式优化 */
:deep(.el-pagination.is-background .el-pager li.is-active) {
  background-color: #409eff;
  color: #fff;
}

.jump-to {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.jump-to .el-input-number {
  width: 80px;
  margin: 0 5px;
}

/* 对话框样式优化 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 15px;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 必填项星号样式 */
:deep(.el-form-item__label)::before {
  content: "" !important;
}
</style>
